package com.googlecode.framework.core.encoder;

import java.util.LinkedList;
import java.util.List;

import org.springframework.util.CollectionUtils;

public class CompositeTextEncoder implements TextEncoder {
    
    private List<TextEncoder> encoders;
    
    public CompositeTextEncoder() {
    }
    
    public CompositeTextEncoder(List<TextEncoder> encoders) {
        this.encoders = encoders;
    }
    
    public void setEncoders(List<TextEncoder> encoders) {
        this.encoders = encoders;
    }
    
    public void addEncoders(List<TextEncoder> encoders) {
        if (CollectionUtils.isEmpty(this.encoders)) {
            emptyEncoders();
        }
        this.encoders.addAll(encoders);
    }
    
    public void addEncoder(TextEncoder encoder) {
        if (CollectionUtils.isEmpty(encoders)) {
            emptyEncoders();
        }
        this.encoders.add(encoder);
    }
    
    protected void emptyEncoders() {
        encoders = new LinkedList<TextEncoder>(); 
    }

    @Override
    public String encode(String text) {
        if (text == null) {
            return null;
        }
        String textToUse = text;
        for (TextEncoder encoder : this.encoders) {
            textToUse = encoder.encode(textToUse);
        }
        return textToUse;
    }
}
